#include "typedef.h"
#include "modbus.h"
#include "uart.h"
#include "systick.h"
#include "MB.h"
#include "config.h"
#include <string.h>

#define MAXSIZE 60
void Digit_display(char *s);
void Special_display(enum show_type id, int16_t num);
void Led_display(uint8_t id, bit status);
void set_digital_flashing(bit sw);

static uint8_t xdata rnum;
static uint8_t xdata tnum;
static uint8_t xdata mb_rbuf[MAXSIZE];
static uint8_t xdata mb_tbuf[MAXSIZE];

static uint8_t uart1_mb_flag;
#define _is_mb_handle_over()     (uart1_mb_flag &   BIT0)
#define _set_mb_handle_over()    (uart1_mb_flag |=  BIT0)
#define _clr_mb_handle_over()    (uart1_mb_flag &= ~BIT0)





void Modbus_Event(void);

void modbus_func(){
	//int16_t s16_data;
	if(uart1_recv_event()){
		Modbus_Event();
		clr_uart1_recv_event();
	}
	//s16_data = 13;
	//Special_display(TYPE_TEMP_C, s16_data);
}


typedef struct
{
	uint8_t head;
	uint8_t str[4];
	uint8_t led;
	uint8_t flash_flag;
	uint8_t power;
	uint8_t check;
	uint8_t tail;
} show_pkt_t;
static show_pkt_t show_pkt; /* Gobal control parameter */
extern bit led_bright;
void set_digit_bright(uint8_t level);

void Modbus_Event(void){
	show_pkt_t *pkt;
	uint8_t     i, sum = 0;
	uint8_t *c;
	rnum = uart1_gets(mb_rbuf);
	if(rnum != sizeof(show_pkt_t)) return;
	c = (uint8_t *)&mb_rbuf;
	pkt = (show_pkt_t *)&mb_rbuf;

	if(pkt->head != 0x5A || pkt->tail != 0xA5) return;

	for(i = 0; i < sizeof(show_pkt_t) - 3; i++){
		sum += *(c + 1 + i);
	}

	if(sum != pkt->check) return;

	Digit_display(&pkt->str);
	if(pkt->flash_flag) set_digital_flashing(1);
	else set_digital_flashing(0);
	
	Led_display(1, (pkt->led >> 0) & 0x01);
	Led_display(2, (pkt->led >> 1) & 0x01);
	Led_display(3, (pkt->led >> 2) & 0x01);
	//Led_display(4, (pkt->led >> 3) & 0x01);
	Led_display(4, 1);
	
	if(pkt->power == ON) set_digit_bright(100);
	else                 set_digit_bright(50);
}
